<template>
  <view class="merchant-orders-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">订单管理</text>
      </view>
    </view>

    <!-- 筛选标签 -->
    <view class="filters">
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'all' }"
        @click="setFilter('all')"
      >全部</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'pending' }"
        @click="setFilter('pending')"
      >待接单</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'preparing' }"
        @click="setFilter('preparing')"
      >备货中</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'shipping' }"
        @click="setFilter('shipping')"
      >配送中</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'delivered' }"
        @click="setFilter('delivered')"
      >已完成</view>
    </view>

    <!-- 订单列表 -->
    <view class="orders-list">
      <view 
        class="order-card" 
        v-for="order in filteredOrders" 
        :key="order.id"
        @click="viewOrderDetail(order.id)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="order-info">
            <text class="order-no">订单 #{{ order.orderNo }}</text>
            <text class="order-time">{{ order.createdAt }}</text>
          </view>
          <text class="order-status" :class="order.status">
            {{ getStatusText(order.status) }}
          </text>
        </view>

        <!-- 用户信息 -->
        <view class="user-info">
          <text class="user-name">👤 {{ order.userName }}</text>
          <text class="user-phone">📱 {{ order.userPhone }}</text>
        </view>

        <!-- 配送信息 -->
        <view class="delivery-info">
          <text class="delivery-address">📍 {{ order.deliveryAddress }}</text>
          <text class="delivery-time">⏰ {{ order.scheduledDeliveryDate }} {{ order.scheduledDeliveryTime }}</text>
        </view>

        <!-- 商品列表 -->
        <view class="order-items">
          <view class="item" v-for="(item, index) in order.items" :key="index">
            <text class="item-name">{{ item.foodName }} x{{ item.quantity }}</text>
            <text class="item-spec" v-if="item.spiceLevel">{{ item.spiceLevel }}</text>
          </view>
        </view>

        <!-- 订单金额 -->
        <view class="order-amount">
          <text class="amount-label">订单金额：</text>
          <text class="amount-value">¥{{ order.totalAmount }}</text>
        </view>

        <!-- 备注 -->
        <view class="order-notes" v-if="order.notes">
          <text class="notes-label">备注：</text>
          <text class="notes-content">{{ order.notes }}</text>
        </view>

        <!-- 操作按钮 -->
        <view class="order-actions" v-if="shouldShowActions(order)">
          <!-- 待接单状态（pending=待支付，paid=已支付待接单）-->
          <template v-if="order.status === 'pending' || order.status === 'paid'">
            <button class="action-btn reject" @click.stop="rejectOrder(order)">拒绝</button>
            <button class="action-btn accept" @click.stop="acceptOrder(order)">接单</button>
          </template>

          <!-- 备货中状态（接单后自动变为此状态）-->
          <template v-if="order.status === 'preparing'">
            <button class="action-btn primary" @click.stop="startShipping(order)">开始配送</button>
          </template>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredOrders.length === 0 && !loading">
        <text class="empty-icon">📦</text>
        <text class="empty-text">暂无{{ getFilterName() }}订单</text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text>加载中...</text>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="bottom-nav">
      <view class="nav-item" @click="goToHome">
        <text class="nav-icon">🏠</text>
        <text class="nav-label">首页</text>
      </view>
      <view class="nav-item active">
        <text class="nav-icon">📋</text>
        <text class="nav-label">订单</text>
      </view>
      <view class="nav-item" @click="goToFoods">
        <text class="nav-icon">🍱</text>
        <text class="nav-label">商品</text>
      </view>
      <view class="nav-item" @click="goToSettings">
        <text class="nav-icon">⚙️</text>
        <text class="nav-label">设置</text>
      </view>
    </view>
    
    <!-- 自定义弹窗 -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import merchantService from '../../../services/merchant.js'
import { backToMerchantHome } from '../../../utils/navigation.js'
import CustomModal from '../../../components/CustomModal.vue'

export default {
  components: {
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      currentFilter: 'all',
      loading: false,
      orders: []
    }
  },
  computed: {
    filteredOrders() {
      if (this.currentFilter === 'all') {
        return this.orders
      }
      // 待接单筛选：包含 pending（待支付）和 paid（已支付待接单）
      if (this.currentFilter === 'pending') {
        return this.orders.filter(order => order.status === 'pending' || order.status === 'paid')
      }
      return this.orders.filter(order => order.status === this.currentFilter)
    }
  },
  onLoad(options) {
    this.getStatusBarHeight()
    
    // 接收筛选参数
    if (options.status) {
      this.currentFilter = options.status
    }
    
    this.loadOrders()
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      
      // 设置CSS变量
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },

    // 加载订单列表
    async loadOrders() {
      this.loading = true
      try {
        const params = {}
        
        // 如果有筛选条件，添加到参数中
        // 注意：pending 筛选不传给后端，因为需要包含 paid 状态
        if (this.currentFilter !== 'all' && this.currentFilter !== 'pending') {
          params.status = this.currentFilter
        }
        
        const response = await merchantService.getOrders(params)
        
        // 格式化订单数据（处理下划线字段名）
        this.orders = (response.data || []).map(order => ({
          ...order,
          // 兼容下划线和驼峰命名
          orderNo: order.orderNo || order.order_no,
          // 用户信息：优先使用收货人信息（deliveryName/deliveryPhone）
          userName: order.userName || order.user_name || order.deliveryName || order.delivery_name,
          userPhone: order.userPhone || order.user_phone || order.deliveryPhone || order.delivery_phone,
          deliveryAddress: order.deliveryAddress || order.delivery_address,
          scheduledDeliveryDate: order.scheduledDeliveryDate || order.scheduled_delivery_date,
          scheduledDeliveryTime: order.scheduledDeliveryTime || order.scheduled_delivery_time,
          totalAmount: order.totalAmount || order.total_amount,
          createdAt: order.createdAt || order.created_at,
          items: (order.items || []).map(item => ({
            foodName: item.foodName || item.food_name,
            quantity: item.quantity,
            spiceLevel: item.spiceLevel || item.spice_level
          }))
        }))
        
        console.log('订单列表（格式化后）:', this.orders)
        console.log('当前筛选:', this.currentFilter)
        console.log('筛选后订单:', this.filteredOrders)
      } catch (error) {
        console.error('加载订单失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.orders = []
      } finally {
        this.loading = false
      }
    },

    // 切换筛选
    setFilter(filter) {
      this.currentFilter = filter
      this.loadOrders()
    },

    // 获取筛选名称
    getFilterName() {
      const nameMap = {
        'all': '',
        'pending': '待接单',
        'preparing': '备货中',
        'shipping': '配送中',
        'delivered': '已完成'
      }
      return nameMap[this.currentFilter] || ''
    },

    // 获取状态文本
    getStatusText(status) {
      return merchantService.getOrderStatusText(status)
    },

    // 判断是否显示操作按钮
    shouldShowActions(order) {
      return !['delivered', 'cancelled', 'refunded'].includes(order.status)
    },

    // 接单
    async acceptOrder(order) {
      this.$refs.customModal.show({
        type: 'confirm',
        title: '确认接单',
        content: `订单金额：¥${order.totalAmount}\n\n确认接受此订单吗？`,
        confirmText: '确认接单',
        cancelText: '取消',
        onConfirm: async () => {
            try {
              await merchantService.acceptOrder(order.id)
              
              uni.showToast({
                title: '接单成功',
                icon: 'success'
              })
              
              // 刷新订单列表
              setTimeout(() => {
                this.loadOrders()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '接单失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 拒单
    async rejectOrder(order) {
      this.$refs.customModal.show({
        type: 'warning',
        title: '拒绝订单',
        content: '确定要拒绝此订单吗？',
        confirmText: '确认拒绝',
        cancelText: '取消',
        showInput: true,
        inputPlaceholder: '请输入拒绝原因（选填）',
        onConfirm: async (inputValue) => {
            try {
              const reason = inputValue || '商家拒绝接单'
              await merchantService.rejectOrder(order.id, reason)
              
              uni.showToast({
                title: '已拒绝订单',
                icon: 'success'
              })
              
              // 刷新订单列表
              setTimeout(() => {
                this.loadOrders()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 开始配送
    async startShipping(order) {
      this.$refs.customModal.show({
        type: 'confirm',
        title: '开始配送',
        content: '确认开始配送吗？',
        confirmText: '开始配送',
        cancelText: '取消',
        onConfirm: async () => {
            try {
              await merchantService.shipOrder(order.id)
              
              uni.showToast({
                title: '已开始配送',
                icon: 'success'
              })
              
              // 刷新订单列表
              setTimeout(() => {
                this.loadOrders()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 查看订单详情
    viewOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/merchant/order-detail/order-detail?id=${orderId}`
      })
    },

    // 返回
    goBack() {
      backToMerchantHome()
    },

    // 导航
    goToHome() {
      uni.navigateTo({
        url: '/pages/merchant/home/home'
      })
    },

    goToFoods() {
      uni.navigateTo({
        url: '/pages/merchant/foods/foods'
      })
    },

    goToSettings() {
      uni.navigateTo({
        url: '/pages/merchant/settings/settings'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.merchant-orders-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 140rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

// 顶部导航栏
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  z-index: 998;
}

.nav-left {
  position: absolute;
  left: 0;
  width: 88rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

// 筛选标签
.filters {
  position: fixed;
  top: calc(var(--status-bar-height) + 88rpx); // 状态栏 + 导航栏
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx;
  display: flex;
  gap: 16rpx;
  overflow-x: auto;
  z-index: 997;
  white-space: nowrap;
  border-bottom: 1rpx solid #eee;
}

.filter-btn {
  flex-shrink: 0;
  padding: 12rpx 24rpx;
  border-radius: 32rpx;
  border: 2rpx solid #ddd;
  font-size: 24rpx;
  color: #666;
  background: #fff;
  
  &.active {
    background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
    border-color: transparent;
    color: #fff;
  }
}

// 订单列表
.orders-list {
  margin-top: calc(var(--status-bar-height) + 88rpx + 100rpx); // 状态栏 + 导航栏 + 筛选栏
  padding: 20rpx;
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-info {
  flex: 1;
}

.order-no {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.order-time {
  display: block;
  font-size: 22rpx;
  color: #999;
}

.order-status {
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 22rpx;
  
  &.pending {
    background: #fff3e0;
    color: #ff8a00;
  }
  
  &.accepted, &.paid {
    background: #e3f2fd;
    color: #2196f3;
  }
  
  &.preparing {
    background: #fff3e0;
    color: #ff8a00;
  }
  
  &.shipping {
    background: #e8f5e9;
    color: #4caf50;
  }
  
  &.delivered {
    background: #f5f5f5;
    color: #999;
  }
}

// 用户信息
.user-info {
  display: flex;
  gap: 24rpx;
  margin-bottom: 12rpx;
}

.user-name, .user-phone {
  font-size: 24rpx;
  color: #666;
}

// 配送信息
.delivery-info {
  margin-bottom: 16rpx;
}

.delivery-address {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.delivery-time {
  display: block;
  font-size: 24rpx;
  color: #ff8a00;
}

// 商品列表
.order-items {
  margin-bottom: 16rpx;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.item-name {
  font-size: 26rpx;
  color: #333;
}

.item-spec {
  font-size: 22rpx;
  color: #ff8a00;
  padding: 2rpx 8rpx;
  background: #fff3e0;
  border-radius: 4rpx;
}

// 订单金额
.order-amount {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 12rpx;
}

.amount-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 8rpx;
}

.amount-value {
  font-size: 32rpx;
  font-weight: 700;
  color: #ff4757;
}

// 备注
.order-notes {
  padding: 12rpx;
  background: #fffbf0;
  border-radius: 8rpx;
  margin-bottom: 16rpx;
}

.notes-label {
  font-size: 22rpx;
  color: #ff8a00;
  margin-right: 8rpx;
}

.notes-content {
  font-size: 22rpx;
  color: #666;
}

// 操作按钮
.order-actions {
  display: flex;
  gap: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-btn {
  flex: 1;
  height: 64rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  border: none;
  
  &.reject {
    background: #fff;
    color: #666;
    border: 2rpx solid #ddd;
  }
  
  &.accept, &.primary {
    background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
    color: #fff;
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 120rpx 0;
}

.empty-icon {
  display: block;
  font-size: 100rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

// 加载状态
.loading-state {
  text-align: center;
  padding: 60rpx 0;
  font-size: 28rpx;
  color: #999;
}

// 底部导航
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-item {
  text-align: center;
  
  &.active {
    .nav-icon {
      font-size: 44rpx;
    }
    .nav-label {
      color: #ff8a00;
      font-weight: 600;
    }
  }
}

.nav-icon {
  display: block;
  font-size: 40rpx;
  margin-bottom: 6rpx;
}

.nav-label {
  display: block;
  font-size: 22rpx;
  color: #666;
}
</style>
